package com.decheng.service.impl;

import com.decheng.dao.BookMapper;
import com.decheng.dto.PaginationDTO;
import com.decheng.pojo.Book;
import com.decheng.service.BookService;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/6/28
 */
@Service
public class BookServiceImpl implements BookService {

    private final BookMapper bookMapper;

    public BookServiceImpl(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    /**
     * 分页查询书籍列表 (首页，图书管理页面)
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PaginationDTO<Book> findBookList(String currentPage, String pageSize) {
        // 1. 检查数据是否有效
        if (StringUtils.isEmptyOrWhitespace(currentPage)) {
            // 当前页为空，默认查询第一页
            currentPage = "1";
        }
        if (StringUtils.isEmptyOrWhitespace(pageSize)) {
            // 页面大小为空，设置默认页面大小
            pageSize = "10";
        }
        // 2. 查询数据总数
        Long count = bookMapper.count();
        // 3. 转换数据类型
        int currentPageInt = Integer.parseInt(currentPage);
        Integer pageSizeInt = Integer.valueOf(pageSize);

        // 3. 检查当前页是否符合规范
        if (currentPageInt > count / pageSizeInt) {
            // 4. 不符合规范，设置默认值
            currentPageInt = 1;
            pageSizeInt = 10;
        }
        // 4. 计算 limit 查询参数
        int start = (currentPageInt - 1) * pageSizeInt;
        List<Book> books = bookMapper.selectListByLimit(start, pageSizeInt);
        PaginationDTO<Book> bp = new PaginationDTO<>();
        bp.setList(books);
        bp.setCurrentPage(currentPageInt);
        bp.setTotalCount(bookMapper.count());
        bp.setPageSize(pageSizeInt);
        return bp;
    }
}
